package com.wjh.rules.common;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class EasyStringUtils {
	
	public static final String PATTERN_OPERATOR = "\\S+ \\S+ \\S+"; //pattern
	
	public static String processTemplate(String template, Map<String, Object> params){
	    StringBuffer sb = new StringBuffer();
//	    Matcher m = Pattern.compile("\\$\\{\\w+\\}").matcher(template);
	    Matcher m = Pattern.compile("\\$\\{\\S+\\}").matcher(template);
	    Map map = params;
	    while (m.find()) {
	        String param = m.group();
//	        String value = (String) params.get(param.substring(2, param.length() - 1));
			String value = getValue(param, map);
			m.appendReplacement(sb, value==null ? "''" : "'"+value+"'");
	    }
	    m.appendTail(sb);
	    return sb.toString();
	}
	
	
    public static boolean matchOperator(String operator) {
		return Pattern.matches(PATTERN_OPERATOR, operator);
	}

	private static String getValue(String param, Map<String, Object> params){
		param = param.substring(2, param.length() - 1);
		String[] split = param.split("\\.");
		for (int i = 0; i < split.length; i++) {
			if (i == split.length-1){
				String valueOf = String.valueOf(params.get(split[i]));
				return valueOf;
			}else {
				params  = (Map)params.get(split[i]);
			}
		}
		return "";
	}
}
